package FreebaseDumps;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import Helper.RandomGenerator;

public class TSVParser {
	private int[] relevantColumnNumbers;
	private boolean isCharacterDumper;
	private RandomGenerator randomGenerator;

	/**
	 * constructs a parser the the .tsv files
	 * @param relvantColumnNumbers - same meaning like in FileDumper
	 * @param isCharacterDumper - same meaning like in FileDumper
	 */
	public TSVParser(int[] relvantColumnNumbers, boolean isCharacterDumper) {
		this.relevantColumnNumbers = relvantColumnNumbers;
		this.isCharacterDumper = isCharacterDumper;
		this.randomGenerator = new RandomGenerator();
	}

	/**
	 * Opens a file
	 * @param file_name - name of file to be opened
	 * @throws FileNotFoundException
	 */
	public void OpenFile(String file_name) throws FileNotFoundException {
		file_reader = new FileReader(file_name);
		buffered_reader = new BufferedReader(file_reader);
	}

	/**
	 * Closes the file that is now open
	 * @throws IOException
	 */
	public void CloseFile() throws IOException {
		buffered_reader.close();
		file_reader.close();
	}

	/**
	 * Parses another line
	 * @return the line to be dumped to our table
	 * @throws IOException
	 */
	public String[] GetNextQuad() throws IOException {
		String line = GetNextLine();

		// no more line - return false
		if (line == null)
			return null;

		// split to tokens
		String[] values = line.split("\t");
		String[] ret = new String[relevantColumnNumbers.length
				+ (isCharacterDumper ? 2 : 0)];
		
		// take the relevant columns
		for (int i = 0; i < relevantColumnNumbers.length; i++)
			ret[i] = relevantColumnNumbers[i] < values.length ? values[relevantColumnNumbers[i]] : "";
		
		// randomly generate hit_points and strength if we're dumping fictional_character
		if (isCharacterDumper) {
			ret[ret.length - 2] = String.valueOf(randomGenerator.getRandomInt(1, 10)); // TODO: constants
			ret[ret.length - 1] = String.valueOf(randomGenerator.getRandomInt(1, 10)); // TODO: constants
		}
		
		return ret;
	}
	
	/**
	 * Reads the next line from file
	 * @return the line
	 * @throws IOException
	 */
	private String GetNextLine() throws IOException {
		return buffered_reader.readLine();
	}

	private FileReader file_reader;
	private BufferedReader buffered_reader;
}
